/*
 * @Project Name: web-home-site
 * @File Name: RequestWrapper.java
 * @Package Name: com.hhly.sns.web.filter
 * @Date: 2017年4月21日上午10:08:48
 * @Creator: yangwentao-840
 * @line------------------------------
 * @修改人:
 * @修改时间:
 * @修改内容:
 */

package com.sm.shoplook.interceptor;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RequestWrapper extends HttpServletRequestWrapper {

	private static final Logger LOG = LoggerFactory.getLogger(RequestWrapper.class);

	public RequestWrapper(HttpServletRequest request) {
		super(request);
	}

	/**
	 * 重写
	 * @see javax.servlet.ServletRequestWrapper#getParameterMap()
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public Map<String, String[]> getParameterMap() {
		Map<String, String[]> requestMap = super.getParameterMap();
		if (MapUtils.isNotEmpty(SensitivityFilter.SENSITIVITIES_MAP)) {
			Iterator iterator = requestMap.entrySet().iterator();
			while (iterator.hasNext()) {
				Map.Entry me = (Map.Entry) iterator.next();
				String[] values = (String[]) me.getValue();
				for (int i = 0; i < values.length; i++) {
					values[i] = sensitivityClean(values[i]);
				}
			}
		}
		return requestMap;
	}

	/**
	 * 重写
	 * @see javax.servlet.ServletRequestWrapper#getParameter(String)
	 */
	@Override
	public String getParameter(String name) {
		String v = super.getParameter(name);
		if (v == null) {
			return null;
		}
		return sensitivityClean(v);
	}

	/**
	 * 重写
	 * @see javax.servlet.ServletRequestWrapper#getParameterValues(String)
	 */
	@Override
	public String[] getParameterValues(String name) {
		String[] v = super.getParameterValues(name);
		if (v == null || v.length == 0) {
			return v;
		}
		for (int i = 0; i < v.length; i++) {
			v[i] = sensitivityClean(v[i]);
		}
		return v;
	}

	@Override
	public String getHeader(String name) {
		String v = super.getHeader(name);
		if (v == null) {
			return null;
		}
		return sensitivityClean(v);
	}

	/**
	 * xss清理，返回安全的字符串
	 * @since 1.0.0
	 * @param value
	 * @return
	 */
	private String sensitivityClean(String value) {
		Set<String> keys = SensitivityFilter.SENSITIVITIES_MAP.keySet();
		for (String key : keys) {
			if (value.contains(key)) {
				value = value.replaceAll(SensitivityFilter.SENSITIVITIES_MAP.get(key), "***");
			}
		}
		return value;
	}
}
